#include "config.hpp"
#include <fstream>
#include <iostream>
#include <iterator>
#include <stdexcept>
#include <string>

AppConfig AppConfig::parse(const std::string &filename) {
	std::ifstream ifs(filename);
	if (!ifs) throw std::runtime_error("Cannot open file");

	std::string content((std::istreambuf_iterator<char>(ifs)), (std::istreambuf_iterator<char>()));

	cJSON *root = cJSON_Parse(content.c_str());
	if (!root) throw std::runtime_error("Invalid JSON");

	AppConfig config;

	// 解析基础字段
	if (auto name = cJSON_GetObjectItem(root, "name")) {
		config.name = name->valuestring;
	}
	if (auto port = cJSON_GetObjectItem(root, "port")) {
		config.port = port->valueint;
	}

	// 解析redis配置
	if (auto redis = cJSON_GetObjectItem(root, "redis")) {
		if (auto host = cJSON_GetObjectItem(redis, "host")) {
			config.redis.host = host->valuestring;
		}
		if (auto port = cJSON_GetObjectItem(redis, "port")) {
			config.redis.port = port->valueint;
		}
	}

	// 解析服务数组
	if (auto services = cJSON_GetObjectItem(root, "services")) {
		if (cJSON_IsArray(services)) {
			for (int i = 0; i < cJSON_GetArraySize(services); i++) {
				cJSON  *item = cJSON_GetArrayItem(services, i);
				Service s;

				if (auto id = cJSON_GetObjectItem(item, "id")) {
					s.id = id->valueint;
				}
				if (auto service = cJSON_GetObjectItem(item, "service")) {
					s.service = service->valuestring;
				}
				if (auto enabled = cJSON_GetObjectItem(item, "enabled")) {
					s.enabled = cJSON_IsTrue(enabled);
				}

				config.services.push_back(std::move(s));
			}
		}
	}

	cJSON_Delete(root);
	return config;
}

void AppConfig::print() const {
	std::cout << "Application Config:\n";
	std::cout << "Name: " << name << "\n";
	std::cout << "Port: " << port << "\n";

	std::cout << "\nRedis Config:\n";
	std::cout << "  Host: " << redis.host << "\n";
	std::cout << "  Port: " << redis.port << "\n";

	std::cout << "\nServices (" << services.size() << "):\n";
	for (size_t i = 0; i < services.size(); i++) {
		const auto &s = services[i];
		std::cout << "[" << i << "] ID: " << s.id << ", Service: " << s.service << ", Enabled: " << (s.enabled ? "true" : "false") << "\n";
	}
}

int main() {
	printf("=== config cpp demo ===\n");
	try {
		auto config = AppConfig::parse("etc/config.json");
		config.print();
	} catch (const std::exception &e) {
		std::cerr << "Error: " << e.what() << std::endl;
		return 1;
	}
	return 0;
}
